<template>
  <div class="roles-container">
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加角色按钮区域 -->
      <el-row>
        <el-col>
          <el-button type="primary" @click="showRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <!-- 角色列表区域 -->
      <el-table :data="rolesList" border stripe>
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template slot-scope="scope">
            <!-- 展开列信息展示区域 -->
            <el-row :class="['bdBottom', index1 === 0 ? 'bdTop' : '' , 'center']" v-for="(item1,index1) in scope.row.children" :key="item1.id">
              <!-- 一级权限 区域 -->
              <el-col :span="5">
                <el-tag type="success"
                  @close="removeRight(scope.row, item1.id)"
                  closable>{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 二级和三级权限 区域 -->
              <el-col :span="19">
                <el-row :class="[ index2 === 0 ? '' : 'bdTop', 'center' ]" 
                  v-for="(item2, index2) in item1.children" 
                  
                  :key="item2.id"
                  >
                  <!-- 二级权限区域 -->
                  <el-col :span="6">
                    <el-tag type="warning"
                      @close="removeRight(scope.row, item2.id)"
                      closable>{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 三级权限区域 -->
                  <el-col :span="18">
                    <el-tag type="danger"  
                      v-for="(item3) in item2.children" 
                      :key="item3.id"
                      @close="removeRight(scope.row, item3.id)"
                      closable>{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#"></el-table-column>
        <el-table-column label="角色名称" prop="roleName"></el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
        <el-table-column label="操作">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <!-- 编辑按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditRoleDialog(scope.row.id)">编辑</el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteRole(scope.row.id)">删除</el-button>
              <!-- 角色管理按钮 -->
              <el-button type="warning" icon="el-icon-setting" size="mini"
                @click="showRightsDialog(scope.row)">分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加角色 弹出框 -->
    <el-dialog title="添加角色" :visible.sync="addRoleVisible" width="50%">
      <el-form :model="addRoleForm" ref="addRoleRef" label-width="70px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 编辑角色 弹出框 -->
    <el-dialog title="编辑角色" :visible.sync="editRoleVisible" width="50%">
      <el-form :model="editRoleForm" ref="editRoleRef" label-width="70px">
        <el-form-item label="角色名称">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="editRole">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配权限 弹出框 -->
    <el-dialog title="分配权限" :visible.sync="rightsVisible" width="50%"
    @close="closeRightsDialog">
      <!-- 树形控件 区域 -->
      <el-tree :data="rightsList" :props="treeProps"
        node-key="id" default-expand-all ref="treeRef"
        show-checkbox :default-checked-keys="treeList"></el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="rightsVisible = false">取 消</el-button>
        <el-button type="primary" @click="updateRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data(){
    return{
      // 角色列表 数组
      rolesList:[],
      // 控制分配权限对话框的出现
      rightsVisible:false,
      // 控制添加角色对话框的出现
      addRoleVisible:false,
      // 控制编辑角色对话框的出现
      editRoleVisible:false,
      // 控制删除角色对话框的出现
      deleteRoleVisible:false,
      // 权限列表 数据(tree)
      rightsList:[],
      // 权限列表树形控件 数据
      treeProps:{
        label:'authName',
        children:'children'
      },
      // 默认选中的节点 数组
      treeList:[],
      // 即将分配权限的角色id
      roleId:"" ,
      // 即将删除的角色id
      // delRoleId:'',
      //添加角色表单数据
      addRoleForm:{
        roleName:'',
        roleDesc:''
      },
      //编辑角色表单数据
      editRoleForm:{
        roleId: '',
        roleName:'',
        roleDesc:''
      },

    }
  },
  created(){
    this.getRoleList();
  },
  methods:{
    // 获取角色列表 方法
    async getRoleList(){
      const { data: res } = await this.$http.get("roles");
      if(res.meta.status !== 200){
        return this.$message.error("获取角色列表失败!");
      }
      this.rolesList = res.data;
      // console.log(this.rolesList);
    },
    // 删除权限 方法
    async removeRight(role, rightId){
      // 提示用户是否确认删除操作
      const confirmResult = await this.$confirm('此操作将永久删除该权限, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).catch(err => err);
        // 如果用户确认删除,返回字符串confirm
        // 如果用户取消删除,返回字符串cancel
        // 判断用户是否真的删除
        if(confirmResult !== 'confirm'){
          return this.$message.info("已取消删除");
        }
        const {data: res} = await this.$http.delete(`roles/${ role.id }/rights/${ rightId }`);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success(res.meta.msg);
        role.children = res.data;
    },
    // 展示分配权限对话框
    async showRightsDialog(role){
      this.roleId = role.id;
      // 请求权限列表数据
      const { data: res } = await this.$http.get("rights/tree");
      if(res.meta.status !== 200){
        return this.$message.error("获取权限列表失败!");
      }
      this.rightsList = res.data;
      this.getRightsId(role, this.treeList);
      console.log("====");
      console.log(this.treeList);
      this.rightsVisible = true;
    },
    // 获取选中节点的id值
    getRightsId(node,arr){
      // 通过递归,判断node是否有children属性,
      //    有,说明不是三级权限,继续递归
      //    没有,说明时三级权限
      if( !node.children ){
        return arr.push(node.id);
      }
      node.children.forEach( item => {
        this.getRightsId(item, arr);
      });
    },
    // 监听 关闭分配权限对话框 事件
    closeRightsDialog(){
      this.treeList = [];
    },
    // 提交分配权限数据 方法
    async updateRights(){
      //调用树形控件自带方法,获取选中和半选中的id
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys()
      ];
      const idStr = keys.join(",");
      // 发起请求
      const { data: res} = await this.$http.post(`roles/${ this.roleId}/rights`, {rids:idStr});
      if(res.meta.status !== 200){
        return this.$message.error("分配权限失败!");
      }
      this.$message.success("分配权限成功!");
      this.getRoleList();
      this.rightsVisible = false;
    },
    // 展示 添加角色 对话框 方法
    showRoleDialog(){
      this.addRoleVisible = true;
    },
    // 添加角色 方法
    async addRole(){
      const { data: res } = await this.$http.post("roles", this.addRoleForm);
      if(res.meta.status !== 201) return this.$message.error(res.meta.msg);
      this.$message.success("添加角色成功！");
      // console.log(res.data);
      this.getRoleList();
      this.addRoleVisible = false;
    },
    // 展示编辑角色对话框 方法
    async showEditRoleDialog(id){
      // this.delRoleId = id;
      const { data: res } = await this.$http.get(`roles/${ id }`);
      if(res.meta.status !== 200){
      this.$message.error(res.meta.msg);
    }
      this.editRoleForm = res.data;
      console.log(this.editRoleForm.roleName);
      this.editRoleVisible = true;
    },
    // 提交编辑角色信息方法
    async editRole(){
      const { data: res } = await this.$http.put(`roles/${ this.editRoleForm.roleId }`,
      { 
        roleName: this.editRoleForm.roleName,
        roleDesc: this.editRoleForm.roleDesc
        });
        if(res.meta.status !== 200){
          // console.log(res);
          this.$message.error(res.meta.msg);
        }else{
          this.$message.success("修改角色信息成功！");
          this.editRoleVisible = false;
          this.getRoleList();
        }
    },
     // 展示删除角色对话框 方法
    async deleteRole(id){
      // 提示用户是否确认删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'error'
        }).catch(err => err);
        // 如果用户确认删除,返回字符串confirm
        // 如果用户取消删除,返回字符串cancel
        // 判断用户是否真的删除
        if(confirmResult !== 'confirm'){
          return this.$message.info("已取消删除");
        }
        const {data: res} = await this.$http.delete("roles/" + id);
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg);
        }
        this.$message.success("成功删除");
        this.getRoleList();
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag{
  margin: 8px;
}
.bdTop{
  border-top: 1px solid #eee;
}
.bdBottom{
  border-bottom: 1px solid #eee;
  padding-left: 20px;
}
.center{
  display: flex;
  align-items: center;
}
</style>